package cn.jhc.social.qq.api.impl;

import java.io.IOException;

import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.social.support.HttpRequestDecorator;

/**
 * QQ的API都需要传入oauth_consumer_key，即应用的appId，
 * ConsumerKeyRequestIntercepter可在RestTemplate中添加该参数。
 * @author luyanfei
 *
 */
public class ConsumerKeyRequestIntercepter implements
		ClientHttpRequestInterceptor {
	private String consumerKey;

	public ConsumerKeyRequestIntercepter(String consumerKey) {
		super();
		this.consumerKey = consumerKey;
	}

	@Override
	public ClientHttpResponse intercept(HttpRequest request, byte[] body,
			ClientHttpRequestExecution execution) throws IOException {
		String path = request.getURI().getPath();
		HttpRequestDecorator decorator = new HttpRequestDecorator(request);
		//获取openid时无需consumer_key
		if(!path.endsWith("me")) {
			decorator.addParameter("oauth_consumer_key", consumerKey);
		}
		return execution.execute(decorator, body);
	}

}